<script setup>
  import { toRefs, watch } from 'vue'
  import { useField } from 'vee-validate'

  import { uniqueId } from '@/helpers/utils'

  /** A Standalone boolean checkbox
   *
   * This checkbox is not intended to offer a multi-choice but to handle a single true/false boolean value.
   *
   * For multi-choice, see CheckBox/CheckboxList
   */
  const props = defineProps({
    modelValue: {
      type: null,
    },
    label: String,
    description: {
      type: String,
      default: '' ,
    },

    name: String,
    value: {
      type: Boolean,
    },
    divCss: {
      type: String,
      default: "toggle",
    },
    editable: { type: Boolean, default: true },
  })
  const emits = defineEmits(['changeValue'])
  const tagId = uniqueId(props.name)

  // we are using toRefs to create reactive references to `name` and `value` props
  // this is important because vee-validate needs to know if any of these props change
  // https://vee-validate.logaretm.com/v4/guide/composition-api/caveats
  const { name } = toRefs(props)
  const { value, checked, handleChange } = useField(name, undefined, {
    type: 'checkbox',
    checkedValue: true,
    uncheckedValue: false,
  })

  // Optionally applies the value initialized as prop
  if (props.value === true || props.value === false) {
    value.value = props.value
  }
  watch(
    () => props.value,
    () => value.value = props.value,
  )

  function onFieldChange(event) {
    handleChange(event)
    emits('changeValue', event.target.checked)
  }
</script>
<template>
  <div class='form-group'>
    <div :class='divCss'>
      <label :for='tagId'>
        <input
          type='checkbox'
          :id='tagId'
          :checked='checked'
          :value='value'
          @change='onFieldChange'
          :name='name'
          :disabled='!editable'
        />
        <span>{{ label }}</span>
      </label>
    </div>
    <div class='help-block' v-if='description' v-html='description' />
  </div>
</template>
